package com.yk.spark.service.analysis.impl;

import com.yk.spark.model.AppModel;
import com.yk.spark.model.FileModel;
import com.yk.spark.service.analysis.api.IAnalysisService;
import com.yk.spark.util.ExcelUtil;
import com.yk.spark.util.SparkFileIO;
import org.springframework.stereotype.Service;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * Created by Limit on 2017/9/4.
 */
@Service("analysisService")
public class AnalysisServiceImpl implements IAnalysisService{
    private SparkFileIO sparkFileIO=SparkFileIO.getSparkFileIo();


    /**
     * 获取app输出结果
     *
     * @param model app实体模型
     * @param limit 最大结果数
     * @return app输出结果
     */
    @Override
    public Map<String, List<Integer>> getAnalysisData(AppModel model, int limit) {

        Map<String,List<Integer>> result=new LinkedHashMap<>();
        List<AnalysisDataModel> dataModelList=new ArrayList<>();
        for(Map.Entry<String,List<Integer>> entry:this.sparkFileIO.sparkAnalysisAppData(model.getAppOutput()).entrySet()){
            dataModelList.add(new AnalysisDataModel(entry.getKey(),entry.getValue()));
        }
        dataModelList.sort(new SortDataModel());
        for (int i = 0; i <limit ; i++) {
            AnalysisDataModel dataModel=dataModelList.get(i);
            result.put(dataModel.key,dataModel.getValue());
        }
        return result;
    }

    /**
     * 导出为Excel
     *
     * @param model        app实体模型
     * @param outputStream Excel文件流输出
     */
    @Override
    public void exportToExcel(AppModel model, OutputStream outputStream) {
        ExcelUtil.exportToExcel(new BufferedOutputStream(outputStream),this.sparkFileIO.sparkAnalysisAppData(model.getAppOutput()));
    }

    private class AnalysisDataModel{

        private String key;
        private List<Integer> value;

        public AnalysisDataModel() {
        }

        public AnalysisDataModel(String key, List<Integer> value) {
            this.key = key;
            this.value = value;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public List<Integer> getValue() {
            return value;
        }

        public void setValue(List<Integer> value) {
            this.value = value;
        }
    }

    private class SortDataModel implements Comparator<AnalysisDataModel>{
        @Override
        public int compare(AnalysisDataModel first, AnalysisDataModel second) {
            return second.getValue().get(0)-first.getValue().get(0);
        }
    }
}
